<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card>
        <el-form
          ref="searchform"
          :inline="true"
          :model="searchform"
          class="demo-form-inline"
          size="small"
        >
          <el-form-item label="组织：" class="inputIds">
            <el-cascader
              v-model="searchform.deptIds"
              clearable
              placeholder="组织"
              :options="depData"
              :props="{ value: 'id', label: 'departName' }"
              :show-all-levels="true"
              :change-on-select="true"
            />
          </el-form-item>
          <!-- <el-form-item label="姓名：">
            <el-input
              v-model="searchform.realname"
              clearable
              placeholder="姓名"
            />
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input
              v-model="searchform.nickname"
              clearable
              placeholder="昵称"
            />
          </el-form-item>
          <el-form-item label="手机：">
            <el-input
              v-model="searchform.mobilephone"
              clearable
              placeholder="手机"
            />
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input
              v-model="searchform.email"
              clearable
              placeholder="邮箱"
            />
          </el-form-item>
          <el-form-item label="微信号：">
            <el-input
              v-model="searchform.wechat"
              clearable
              placeholder="微信号"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch()">查询</el-button>
            <el-button type="default" @click="handleClean()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <!-- <div class="list-btn-container">
        <el-button-group>
          <el-button
            v-hasPermi="['Sys_user/Add']"
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="ShowEditOrViewDialog()"
          >新增</el-button>
          <el-button
            v-hasPermi="['Sys_user/Edit']"
            type="primary"
            icon="el-icon-edit"
            class="el-button-modify"
            size="small"
            @click="ShowEditOrViewDialog('edit')"
          >修改</el-button>
          <el-button
            v-hasPermi="['Sys_user/Enable']"
            type="info"
            icon="el-icon-video-pause"
            size="small"
            @click="setEnable('0')"
          >禁用</el-button>
          <el-button
            v-hasPermi="['Sys_user/Enable']"
            type="success"
            icon="el-icon-video-play"
            size="small"
            @click="setEnable('1')"
          >启用</el-button>
          <el-button
            v-hasPermi="['Sys_user/DeleteSoft']"
            type="warning"
            icon="el-icon-delete"
            size="small"
            @click="deleteSoft('0')"
          >软删除</el-button>
          <el-button
            v-hasPermi="['Sys_user/Delete']"
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="deletePhysics()"
          >删除</el-button>
          <el-button
            type="default"
            icon="el-icon-refresh"
            size="small"
            @click="loadTableData()"
          >刷新</el-button>
        </el-button-group>
      </div> -->
      <el-table
        ref="gridtable"
        v-loading="tableloading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        :default-sort="{ prop: 'SortCode', order: 'ascending' }"
        @select="handleSelectChange"
        @select-all="handleSelectAllChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" />
        <!-- <el-table-column prop="account" label="账号" sortable="custom" width="120" /> -->
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="realname" label="真实姓名" />
        <el-table-column prop="username" label="用户名" />
        <!-- <el-table-column
          prop="HeadIcon"
          label=""
          sortable="custom"
          width="120"
        />
        <el-table-column prop="Gender" label="" sortable="custom" width="120" /> -->
        <!-- <el-table-column prop="birthday" label="生日" sortable="custom" width="120" />
        <el-table-column prop="mobilephone" label="手机号" sortable="custom" width="120" />
        <el-table-column prop="email" label="邮箱" sortable="custom" width="120" />
        <el-table-column prop="wechat" label="微信" sortable="custom" width="120" /> -->
        <!-- <el-table-column
          prop="ManagerId"
          label=""
          sortable="custom"
          width="120"
        /> -->
        <!-- <el-table-column
          prop="SecurityLevel"
          label=""
          sortable="custom"
          width="120"
        /> -->
        <!-- <el-table-column
          prop="Signature"
          label=""
          sortable="custom"
          width="120"
        /> -->
        <!-- <el-table-column
          prop="国家"
          label="country"
          sortable="custom"
          width="120"
        />
        <el-table-column
          prop="省"
          label="province"
          sortable="custom"
          width="120"
        />
        <el-table-column prop="city" label="" sortable="custom" width="120" />
        <el-table-column
          prop="市"
          label="District"
          sortable="custom"
          width="120"
        />
        <el-table-column
          prop="OrganizeId"
          label=""
          sortable="custom"
          width="120"
        />
        <el-table-column
          prop="DepartmentId"
          label=""
          sortable="custom"
          width="120"
        /> -->
        <!-- <el-table-column prop="RoleId" label="" sortable="custom" width="120" />
        <el-table-column prop="DutyId" label="" sortable="custom" width="120" /> -->
        <!-- <el-table-column
          prop="isadministrator"
          label="是否管理员"
          sortable="custom"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.isadministrator === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.isadministrator === true ? "是" : "否" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="ismember"
          label="是否会员"
          sortable="custom"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.ismember === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.ismember === true ? "是" : "否" }}</el-tag>
          </template>
        </el-table-column> -->
        <!-- <el-table-column
          prop="MemberGradeId"
          label=""
          sortable="custom"
          width="120"
        /> -->
        <!-- <el-table-column
          label="是否启用"
          sortable="custom"
          width="120"
          prop="enabledmark"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.enabledmark === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.enabledmark === true ? "启用" : "禁用" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="creatortime"
          label="创建时间"
          sortable="custom"
          width="160"
        /> -->
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <!--<el-button type="text" size="small" @click="deletePhysics(scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="editDialog(scope.row)">修改</el-button>-->
            <el-button
              v-show="scope.row.isadmin===false"
              type="text"
              size="small"
              @click="setSystemAdmin(scope.row)"
            >设置管理员</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="pagination-container">
        <el-pagination
          background
          :current-page="pagination.currentPage"
          :page-sizes="[5, 10, 20, 50, 100, 200, 300, 400]"
          :page-size="pagination.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </el-card>
    <el-dialog
      ref="dialogEditForm"
      v-el-drag-dialog
      :title="editFormTitle + '{ModelTypeDesc}'"
      :visible.sync="dialogEditFormVisible"
      width="660px"
      append-to-body
    >
      <el-form ref="editFrom" :model="editFrom" :rules="rules">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="Account">
          <el-input
            v-model="editFrom.Account"
            placeholder="请输入账号"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="姓名"
          :label-width="formLabelWidth"
          prop="RealName"
        >
          <el-input
            v-model="editFrom.RealName"
            placeholder="请输入姓名"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          prop="NickName"
        >
          <el-input
            v-model="editFrom.NickName"
            placeholder="请输入昵称"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="Gender">
          <el-radio-group v-model="editFrom.Gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="出身日期"
          :label-width="formLabelWidth"
          prop="Birthday"
        >
          <el-date-picker
            v-model="editFrom.Birthday"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="手机"
          :label-width="formLabelWidth"
          prop="MobilePhone"
        >
          <el-input
            v-model="editFrom.MobilePhone"
            placeholder="请输入手机"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="Email">
          <el-input
            v-model="editFrom.Email"
            placeholder="请输入邮箱"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="选项" :label-width="formLabelWidth" prop="">
          <el-checkbox v-model="editFrom.EnabledMark">启用</el-checkbox>
          <el-checkbox v-model="editFrom.IsAdministrator">管理员</el-checkbox>
        </el-form-item>
        <!-- <el-form-item label="所属组织" :label-width="formLabelWidth" prop="DepartmentId">
          <el-cascader v-model="selectedOrganizeOptions" style="width:500px;" :options="selectOrganize" filterable :props="{label:'FullName',value:'Id',children:'Children',emitPath:false, checkStrictly: true,expandTrigger: 'hover' }" clearable @change="handleSelectOrganizeChange" />
        </el-form-item> -->
        <!-- <el-form-item label="岗位角色" :label-width="formLabelWidth" prop="RoleId">
          <el-select v-model="editFrom.RoleId" style="width:500px" multiple clearable placeholder="请选择">
            <el-option v-for="item in selectRole" :key="item.Id" :label="item.FullName" :value="item.Id" />
          </el-select>
        </el-form-item> -->
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          prop="Description"
        >
          <el-input
            v-model="editFrom.Description"
            style="width: 500px"
            placeholder=""
            autocomplete="off"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveEditForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'digitalcertificate', // 需与菜单的功能编码一致
  data() {
    return {
      searchform: {
        keywords: '',
        realname: '',
        nickname: '',
        mobilephone: '',
        email: '',
        wechat: '',
        deptIds: ''
      },
      tableData: [],
      tableloading: true,
      pagination: {
        currentPage: 1,
        pagesize: 20,
        pageTotal: 0
      },
      sortableData: {
        order: 'desc',
        sort: 'CreatorTime'
      },
      dialogEditFormVisible: false,
      editFormTitle: '',
      editFrom: {},
      rules: {},
      formLabelWidth: '80px',
      currentId: '', // 当前操作对象的ID值，主要用于修改
      currentSelected: [],
      depData: []
    }
  },
  created() {
    this.pagination.currentPage = 1
    this.InitDictItem()
    this.tableloading = false
  },
  methods: {
    setSystemAdmin(rowData) {
      console.log(rowData)
      const postData = {
        account: rowData.username,
        creatoruserid: this.$store.state.user.userid,
        deletemark: false,
        enabledmark: true,
        id: 0,
        isadministrator: true,
        ismember: true,
        membergradeid: this.searchform.deptIds[this.searchform.deptIds.length - 1],
        mobilephone: rowData.username,
        nickname: rowData.username,
        organizeid: this.searchform.deptIds[this.searchform.deptIds.length - 1],
        realname: rowData.realname,
        referraluserid: rowData.id,
        securitylevel: 0,
        roleid:'5'
      }
      modifySystemAdmin(postData).then((res) => {
        console.log(res.data)
        if (res.data) {
          this.$message.success('设置成功!')
          this.loadTableData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    /**
     * 初始化数据
     */
    InitDictItem() {
      console.log(this.$store.state.user)
      get_all_depart({ detIds: this.$store.state.user.organizeid }).then(
        (res) => {
          this.depData = getTreeData(res.data)
          console.log(this.depData)
        }
      )
    },

    // 取消按钮
    cancel() {
      this.dialogEditFormVisible = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.editFrom = {
        Account: '',
        RealName: '',
        NickName: '',
        HeadIcon: '',
        Gender: '',
        Birthday: '',
        MobilePhone: '',
        Email: '',
        WeChat: '',
        ManagerId: '',
        SecurityLevel: '',
        Signature: '',
        Country: '',
        Province: '',
        City: '',
        District: '',
        OrganizeId: '',
        DepartmentId: '',
        RoleId: '',
        DutyId: '',
        IsAdministrator: '',
        IsMember: '',
        MemberGradeId: '',
        ReferralUserId: '',
        UnionId: '',
        SortCode: '',
        DeleteMark: '',
        EnabledMark: '',
        Description: '',
        CreatorTime: '',
        CreatorUserId: '',
        LastModifyTime: '',
        LastModifyUserId: '',
        DeleteTime: '',
        DeleteUserId: '',
        WechatOpenId: ''

        // 需个性化处理内容
      }
      this.resetForm('editFrom')
    },

    handleClean: function() {
      this.searchform = {
        nickname: '',
        realname: '',
        wechat: '',
        mobilephone: '',
        email: '',
        deptIds: ''
      }
      this.loadTableData()
    },
    /**
     * 加载页面table数据
     */
    loadTableData: function() {
      this.tableloading = true
      const condition = []
      if (this.searchform.nickname !== '') {
        condition.push({
          column: 'nickname',
          type: 'like',
          value: this.searchform.nickname
        })
      } else if (this.searchform.realname !== '') {
        condition.push({
          column: 'realname',
          type: 'like',
          value: this.searchform.realname
        })
      } else if (this.searchform.mobilephone !== '') {
        condition.push({
          column: 'mobilephone',
          type: 'like',
          value: this.searchform.mobilephone
        })
      } else if (this.searchform.email !== '') {
        condition.push({
          column: 'email',
          type: 'like',
          value: this.searchform.email
        })
      } else if (this.searchform.wechat !== '') {
        condition.push({
          column: 'wechat',
          type: 'like',
          value: this.searchform.wechat
        })
      }
      // else if (this.searchform.deptIds !== '') {
      //   condition.push({ column: 'departmentid', type: 'eq', value: this.searchform.deptIds[0] })
      // }

      var seachdata = {
        condition: JSON.stringify(condition),
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pagesize,
        Order: this.sortableData.order,
        Sort: this.sortableData.sort,
        deptIds: this.searchform.deptIds[this.searchform.deptIds.length - 1]
      }
          if (this.searchform.deptIds !== '') { 
          seachdata.deptIds= this.searchform.deptIds[this.searchform.deptIds.length - 1] 
      }
      else{
        seachdata.deptIds= this.$store.state.user.organizeid 
      }
      get_user_list(seachdata).then((res) => {
        this.tableData = res.data
        this.pagination.pageTotal = res.data.total
        this.tableloading = false
      })
    },
    /**
     * 点击查询
     */
    handleSearch: function() {
      this.pagination.currentPage = 1
      this.loadTableData()
    },

    /**
     * 新增、修改或查看明细信息（绑定显示数据）     *
     */
    ShowEditOrViewDialog: function(view) {
      this.reset()
      if (view !== undefined) {
        if (
          this.currentSelected.length > 1 ||
          this.currentSelected.length === 0
        ) {
          this.$alert('请选择一条数据进行编辑/修改', '提示')
        } else {
          this.currentId = this.currentSelected[0].Id
          this.editFormTitle = '编辑'
          this.dialogEditFormVisible = true
          this.bindEditInfo()
        }
      } else {
        this.editFormTitle = '新增'
        this.currentId = ''
        this.dialogEditFormVisible = true
      }
    },
    bindEditInfo: function() {
      getSys_userDetail(this.currentId).then((res) => {
        this.editFrom = res.data
        // 需个性化处理内容
      })
    },
    /**
     * 新增/修改保存
     */
    saveEditForm() {
      this.$refs['editFrom'].validate((valid) => {
        if (valid) {
          const data = {
            Account: this.editFrom.Account,
            RealName: this.editFrom.RealName,
            NickName: this.editFrom.NickName,
            HeadIcon: this.editFrom.HeadIcon,
            Gender: this.editFrom.Gender,
            Birthday: this.editFrom.Birthday,
            MobilePhone: this.editFrom.MobilePhone,
            Email: this.editFrom.Email,
            WeChat: this.editFrom.WeChat,
            ManagerId: this.editFrom.ManagerId,
            SecurityLevel: this.editFrom.SecurityLevel,
            Signature: this.editFrom.Signature,
            Country: this.editFrom.Country,
            Province: this.editFrom.Province,
            City: this.editFrom.City,
            District: this.editFrom.District,
            OrganizeId: this.editFrom.OrganizeId,
            DepartmentId: this.editFrom.DepartmentId,
            RoleId: this.editFrom.RoleId,
            DutyId: this.editFrom.DutyId,
            IsAdministrator: this.editFrom.IsAdministrator,
            IsMember: this.editFrom.IsMember,
            MemberGradeId: this.editFrom.MemberGradeId,
            ReferralUserId: this.editFrom.ReferralUserId,
            UnionId: this.editFrom.UnionId,
            SortCode: this.editFrom.SortCode,
            DeleteMark: this.editFrom.DeleteMark,
            EnabledMark: this.editFrom.EnabledMark,
            Description: this.editFrom.Description,
            CreatorTime: this.editFrom.CreatorTime,
            CreatorUserId: this.editFrom.CreatorUserId,
            LastModifyTime: this.editFrom.LastModifyTime,
            LastModifyUserId: this.editFrom.LastModifyUserId,
            DeleteTime: this.editFrom.DeleteTime,
            DeleteUserId: this.editFrom.DeleteUserId,
            WechatOpenId: this.editFrom.WechatOpenId,

            Id: this.currentId
          }

          var url = 'Sys_user/Insert'
          if (this.currentId !== '') {
            url = 'Sys_user/Update'
          }
          saveSys_user(data, url).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.dialogEditFormVisible = false
              this.currentSelected = ''
              this.loadTableData()
              this.InitDictItem()
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    setEnable: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = []
        this.currentSelected.forEach((element) => {
          currentIds.push(element.Id)
        })
        const data = {
          Ids: currentIds,
          Flag: val
        }
        setSys_userEnable(data).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      }
    },
    deleteSoft: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        const that = this
        this.$confirm('是否确认删除所选的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function() {
            var currentIds = []
            that.currentSelected.forEach((element) => {
              currentIds.push(element.Id)
            })
            const data = {
              Ids: currentIds,
              Flag: val
            }
            return deleteSoftSys_user(data)
          })
          .then((res) => {
            if (res.code === 200) {
              that.$message({
                message: '删除成功',
                type: 'success'
              })
              that.currentSelected = ''
              that.loadTableData()
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
      }
    },
    deletePhysics: function() {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        const that = this
        this.$confirm('是否确认删除所选的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function() {
            var currentIds = []
            that.currentSelected.forEach((element) => {
              currentIds.push(element.Id)
            })
            const data = {
              Ids: currentIds
            }
            return deleteSys_user(data)
          })
          .then((res) => {
            if (res.code === 200) {
              that.$message({
                message: '删除成功',
                type: 'success'
              })
              that.currentSelected = ''
              that.loadTableData()
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
      }
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChange: function(column) {
      this.sortableData.sort = column.prop
      if (column.order === 'ascending') {
        this.sortableData.order = 'asc'
      } else {
        this.sortableData.order = 'desc'
      }
      this.loadTableData()
    },
    /**
     * 当用户手动勾选checkbox数据行事件
     */
    handleSelectChange: function(selection, row) {
      this.currentSelected = selection
    },
    /**
     * 当用户手动勾选全选checkbox事件
     */
    handleSelectAllChange: function(selection) {
      this.currentSelected = selection
    },
    /**
     * 选择每页显示数量
     */
    handleSizeChange(val) {
      this.pagination.pagesize = val
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    /**
     * 选择当页面
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTableData()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
